package ext.mango.aa.po;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import mango.functions.FuncDate;
import mango.functions.FuncString;
import mango.orm.DaoFactory;
import mango.orm.DBSession;
import mango.orm.DBSessionFactory;
import mango.orm.entity.Entity;
import mango.web.Info;
import ext.mango.aa.eo.EOAAMenuToUserGroup;
import ext.mango.aa.eo.EOAAUserGroup;
import ext.mango.base.Messages;
import ext.mango.base.POBase;

public class GroupManager extends POBase {
    public boolean queryGroup() {
        String sql = "select usergroupid QUERYGRPID, usergroupid GRPID, usergroupname GROUPNAME, REMARK, MAKEDATE, operator from AAUserGroup"; //$NON-NLS-1$
        String group = this.getRequestParameter("GROUPID"); //$NON-NLS-1$
        if (!FuncString.isBlank(group)) {
            sql += " where usergroupid=@groupid or usergroupname like @groupname"; //$NON-NLS-1$
        }
        List<Entity> ret = DaoFactory.c(sql).setParamByName("groupid", group).setParamByName("groupname","%"+group+"%").listQuery(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
        this.setResult(Entity.toJSON(ret, "group")); //$NON-NLS-1$
        return true;
    }

    public boolean addgroup() {
        String groupId = this.getRequestParameter("GRPID"); //$NON-NLS-1$
        String groupName = this.getRequestParameter("GROUPNAME"); //$NON-NLS-1$
        String remark = this.getRequestParameter("REMARK"); //$NON-NLS-1$
        String menus = this.getRequestParameter("MENUS"); //$NON-NLS-1$
        menus = menus.substring(0, menus.length() - 1);
        logger.debug("menus --> " + menus); //$NON-NLS-1$
        String chksql = "select '1' from AAUserGroup where usergroupid=?"; //$NON-NLS-1$
        String chkret = DaoFactory.c(chksql).setParameter(groupId).getStringValue();
        if (!FuncString.isBlank(chkret)) {
            this.addInfo(Info.ERROR, Messages.getString(this.getLanguage(),"usergroupexists")); //$NON-NLS-1$
            return false;
        }

        EOAAUserGroup userGroup = new EOAAUserGroup().setUserGroupId(groupId)
                .setUserGroupName(groupName).setRemark(remark).setMakeDate(new Date())
                .setMakeTime(FuncDate.getCurrentTime()).setOperator(this.getCurrentUser().getId());
        
        HashSet<String> menuSet = new HashSet<String>();
        String[] menuIds = menus.split(","); //$NON-NLS-1$
        String queryParent = "select parent from AAMenu where id=?"; //$NON-NLS-1$
        for (String menuId : menuIds) {
            String pid = DaoFactory.c(queryParent).setParameter(menuId).getStringValue();
            menuSet.add(menuId);
            menuSet.add(pid);
        }
        Iterator<String> iter = menuSet.iterator();
        List<EOAAMenuToUserGroup> mgs = new ArrayList<EOAAMenuToUserGroup>();
        while(iter.hasNext()) {
            EOAAMenuToUserGroup eo = new EOAAMenuToUserGroup().setUserGroupId(groupId).setMenuId(iter.next());
            mgs.add(eo);
        }
        DBSession session = DBSessionFactory.getSession();
        session.save(userGroup);
        session.save(mgs);
        session.commit();
        this.addInfo(Info.SUCCESS, Messages.getString(this.getLanguage(),"usergroupcreatesuccess")); //$NON-NLS-1$
        return true;
    }
    
    public boolean updategroup(){
        String groupId = this.getRequestParameter("GRPID"); //$NON-NLS-1$
        if("Super".equals(groupId)) { //$NON-NLS-1$
            this.addInfo(Info.ERROR, Messages.getString(this.getLanguage(),"usergroup") + groupId + Messages.getString(this.getLanguage(),"cantchange")); //$NON-NLS-1$ //$NON-NLS-2$
            return false;
        }
        String groupName = this.getRequestParameter("GROUPNAME"); //$NON-NLS-1$
        String remark = this.getRequestParameter("REMARK"); //$NON-NLS-1$
        String menus = this.getRequestParameter("MENUS"); //$NON-NLS-1$
        menus = menus.substring(0, menus.length() - 1);
        logger.debug("menus --> " + menus); //$NON-NLS-1$
        EOAAUserGroup userGroup = new EOAAUserGroup().setUserGroupId(groupId)
        .setUserGroupName(groupName).setRemark(remark).setMakeDate(new Date())
        .setMakeTime(FuncDate.getCurrentTime()).setOperator(this.getCurrentUser().getId());
        HashSet<String> menuSet = new HashSet<String>();
        String[] menuIds = menus.split(","); //$NON-NLS-1$
        String queryParent = "select parent from AAMenu where id=?"; //$NON-NLS-1$
        for (String menuId : menuIds) {
            String pid = DaoFactory.c(queryParent).setParameter(menuId).getStringValue();
            menuSet.add(menuId);
            menuSet.add(pid);
        }
        Iterator<String> iter = menuSet.iterator();
        List<EOAAMenuToUserGroup> mgs = new ArrayList<EOAAMenuToUserGroup>();
        while(iter.hasNext()) {
            EOAAMenuToUserGroup eo = new EOAAMenuToUserGroup().setUserGroupId(groupId).setMenuId(iter.next());
            mgs.add(eo);
        }
        String delSql = "delete from AAMenuToUserGroup where usergroupid=?"; //$NON-NLS-1$
        DBSession session = DBSessionFactory.getSession();
        session.update(userGroup);
        session.execute(delSql, groupId);
        session.save(mgs);
        session.commit();
        this.addInfo(Info.SUCCESS, Messages.getString(this.getLanguage(),"usergroupupdatesuccess")); //$NON-NLS-1$
        return true;
    }
    
    public boolean deletegroup(){
        String groupId = this.getRequestParameter("GRPID"); //$NON-NLS-1$
        if("Super".equals(groupId) || "Base".equals(groupId)) { //$NON-NLS-1$ //$NON-NLS-2$
            this.addInfo(Info.ERROR, Messages.getString(this.getLanguage(),"usergroup") + groupId + Messages.getString(this.getLanguage(),"cantdelete")); //$NON-NLS-1$ //$NON-NLS-2$
            return false;
        }
        String sql1 = "delete from AAUserGroup where usergroupid=?";
        String sql2 = "delete from AAMenuToUserGroup where usergroupid=?"; //$NON-NLS-1$
        String sql3 = "delete from AAUserToUserGroup where usergroupid=?"; //$NON-NLS-1$
        DBSession session = DBSessionFactory.getSession();
        session.execute(sql1, groupId);
        session.execute(sql2, groupId);
        session.execute(sql3, groupId);
        session.commit();
        this.addInfo(Info.SUCCESS, Messages.getString(this.getLanguage(),"usergroupdeletesuccess")); //$NON-NLS-1$
        return true;
    }
    
    public void handleException(Exception e) {
        if ("addgroup".equals(this.getMethod())){ //$NON-NLS-1$
            this.addInfo(Info.ERROR, Messages.getString(this.getLanguage(),"usergroupcreatefailed")); //$NON-NLS-1$
        }
        else if("deletegroup".equals(this.getMethod())){ //$NON-NLS-1$
            this.addInfo(Info.SUCCESS, Messages.getString(this.getLanguage(),"usergroupdeletefailed")); //$NON-NLS-1$
        }
    }
}
